import React from 'react'
import RoomTag from "./RoomTag/room_tag";
import styles from "../styles/Home.module.css";
import RoomEnter from "./RoomTag/room_enter";
import ChatDialog from "./Chat/ChatDialog";
import {Modal} from "react-bootstrap";
import {getPersonInRoom} from "../service/service";
import Image from 'next/image'
import {apiBase} from "../service/service";

// let roomInfo={
//   roomName:'',
//   chatInfos:[], //chatInfo数组
//   socket:{},
//   myName:''
// }

// let chatInfo={
//   senderName:'',
//   content:'',
//   time:'',
//   isSystem:false
//   msgId:'',
//   type:'',
//   avatarUrl:''
// }

//侧边栏room列表
// room{
//   roomName, lastMsg,msgTime
// }

function buildLastMsg(chatInfo) {
  if (chatInfo.type === 'TXT') {

  }
}


export default class ChatRooms extends React.Component {

  ROOM_INFOS = [] //roomInfo数组
  curSock = {} //当前聊天室的websocket连接

  constructor(props) {
    super(props);
    this.state = {
      curMyName: '',
      curRoomName: '',
      curChatInfos: [],
      rooms: [],
      showModal: false,
      curRoomMember: [],
    }
  }

  componentWillUnmount() {
    this.ROOM_INFOS.forEach(roomInfo => {
      roomInfo.socket.close();
    })
  }

  onConnectSuc = (roomName, myName, wsCon) => {
    const room = this.ROOM_INFOS.find(roomInfo => roomInfo.roomName === roomName)
    if (room) {
      return
    }

    this.ROOM_INFOS.push({roomName, socket: wsCon, myName, chatInfos: []})
    this.curSock = wsCon
    this.setState(prev => ({
      rooms: [...prev.rooms, {roomName: roomName, lastMsg: '', msgTime: ''}],
      curMyName: myName,
      curRoomName: roomName,
      curChatInfos: []
    }))
  }

  onMessageCome = (roomName, data) => {
    //全局存储相关信息
    const chatInfo = JSON.parse(data)
    const roomInfo = this.ROOM_INFOS.find(roomInfo => {
      return roomInfo.roomName === roomName
    })
    if (!roomInfo) {
      console.error("没有找到" + roomName)
      return
    }
    roomInfo.chatInfos.push(chatInfo)

    //更新当前聊天窗口
    if (this.state.curRoomName === roomName) {
      this.setState(prev => ({
        curChatInfos: [...prev.curChatInfos, chatInfo]
      }))
    }

    //rooms的lastMsg更新
    if (chatInfo.isSystem) {
      return
    }

    let lastMsg = ''
    if (chatInfo.type === 'TXT') {
      lastMsg = chatInfo.senderName + ":" + chatInfo.content
      if (lastMsg.length > 9) {
        lastMsg = lastMsg.substr(0, 9) + "..."
      }
    } else if (chatInfo.type === 'PIC') {
      lastMsg = chatInfo.senderName + ":【图片】"
    } else {
      lastMsg = chatInfo.senderName + ":【文件】"
    }


    const newRooms = this.state.rooms.map(r => {
      return r.roomName === roomName ? {...r, msgTime: chatInfo.time, lastMsg} : r
    })
    this.setState({
      rooms: newRooms
    })
  }

  roomTagOnClick = (roomName) => {
    const roomInfo = this.ROOM_INFOS.find(roomInfo => {
      return roomInfo.roomName === roomName
    })
    if (!roomInfo) {
      console.error("没有找到" + roomName)
      return
    }
    this.curSock = roomInfo.socket
    this.setState({
      curMyName: roomInfo.myName,
      curRoomName: roomInfo.roomName,
      curChatInfos: roomInfo.chatInfos
    })
  }

  sendMsg = (roomName, message) => {
    if (roomName !== this.state.curRoomName) {
      console.error("不是当前房间！！")
      return
    }
    this.curSock.send(message);
  }

  onLeaveRoom = roomName => {
    const room = this.ROOM_INFOS.find(roomInfo => roomInfo.roomName === roomName)
    if (!room) {
      return
    }
    room.socket.close()

    //删除全局roominfos
    this.ROOM_INFOS = this.ROOM_INFOS.filter(roomInfo => roomInfo.roomName !== roomName)
    //删除rooms
    const newRooms = this.state.rooms.filter(r => r.roomName !== roomName)
    this.setState({rooms: newRooms})
    //如果是当前聊天窗口，需要切换窗口
    if (this.state.curRoomName === room.roomName) {
      if (this.ROOM_INFOS.length > 0) {
        const nextRoomInfo = this.ROOM_INFOS[0]
        this.curSock = nextRoomInfo.socket
        this.setState({
          curMyName: nextRoomInfo.myName,
          curRoomName: nextRoomInfo.roomName,
          curChatInfos: nextRoomInfo.chatInfos
        })
      } else {
        this.curSock = {}
        this.setState({
          curMyName: '',
          curRoomName: '',
          curChatInfos: ''
        })
      }
    }
  }

  enterRoomCheck = (roomName) => {
    const room = this.ROOM_INFOS.find(room => room.roomName === roomName)
    return !!room
  }

  clearCurChat = () => {
    this.setState(prev => ({
      rooms: prev.rooms.map(room => room.roomName === this.state.curRoomName ? {...room, lastMsg: ""} : room),
      curChatInfos: []
    }))
  }

  showCurRoomMember = async () => {
    const persons = await getPersonInRoom(this.state.curRoomName)
    this.setState({
      showModal: true,
      curRoomMember: persons
    })
  }


  render() {
    const tagList = this.state.rooms.map((room) => <RoomTag onClick={this.roomTagOnClick} key={room.roomName}
                                                            roomName={room.roomName}
                                                            lastMsg={room.lastMsg}
                                                            msgTime={room.msgTime}
                                                            onLeaveCallback={this.onLeaveRoom}
                                                            isSelect={room.roomName === this.state.curRoomName}/>)

    const roomMembers = this.state.curRoomMember.map(person =>
      <div key={person.nickName} style={{float: "left",marginLeft:"10px"}}>
        <Image src={apiBase + person.avatarUrl} height={65} width={65}/>
        <div style={{textAlign:"center"}}>{person.nickName}</div>
      </div>
    )

    return this.state.curRoomName ?
      (
        <div className={styles.main}>
          <div>
            <RoomEnter connectSuccessCallback={this.onConnectSuc} messageCallback={this.onMessageCome}
                       checkRoomHasEnter={this.enterRoomCheck}/>
            <div className={styles.roomTagList}>
              {tagList}
            </div>
          </div>
          <div>
            <ChatDialog roomName={this.state.curRoomName} chatInfos={this.state.curChatInfos}
                        myName={this.state.curMyName} clearChatCallback={this.clearCurChat}
                        sendMsgCallback={this.sendMsg} showMemberCallback={this.showCurRoomMember}/>
          </div>
          <Modal show={this.state.showModal} size="lg" onHide={() => this.setState({showModal: false})} centered={true}>
            <Modal.Body>
              {roomMembers}
            </Modal.Body>
          </Modal>
        </div>

      ) : (
        <div style={{
          width: 150,
          height: 70,
          margin: 'auto',
          top: 0,
          bottom: 0,
          left: 0,
          right: 0,
          position: 'absolute'
        }}>
          <RoomEnter connectSuccessCallback={this.onConnectSuc} messageCallback={this.onMessageCome}
                     checkRoomHasEnter={this.enterRoomCheck}/>
        </div>

      )
  }
}
